//
//  MarketController.m
//  TimeTallyDemo
//
//  Created by mac on 2019/10/15.
//  Copyright © 2019 gongwenkai. All rights reserved.
//

#import "MarketController.h"
#import "MarketCell.h"
#import "MarketModel.h"

@interface MarketController () <UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *mainTableV;

@property (nonatomic, strong) NSArray *mainArray;

@end

static NSString *cellid = @"cellid";

@implementation MarketController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"行情";
    
    self.mainTableV.dataSource = self;
    self.mainTableV.delegate = self;
    self.mainTableV.tableFooterView = [UIView new];
    self.mainTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.mainTableV registerNib:[UINib nibWithNibName:@"MarketCell" bundle:nil] forCellReuseIdentifier:cellid];
    // 默认的下拉刷新和上拉加载
    self.mainTableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 这个地方是网络请求的处理
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.mainTableV.mj_header endRefreshing];
            [self.mainTableV reloadData];
        });
        
    }];
    
    self.mainTableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 这个地方是网络请求的处理
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.mainTableV.mj_footer endRefreshing];
        });
    }];
}

- (NSArray *)mainArray {
    
    if (!_mainArray) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"market" ofType:@"json"];
        NSData *data = [[NSData alloc] initWithContentsOfFile:path];
        NSError *error;
        NSArray *maskets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        if (error) {
            _mainArray = [NSArray array];
        }else {
            _mainArray = [MarketModel mj_objectArrayWithKeyValuesArray:maskets];
        }
    }
    
    return _mainArray;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.mainArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MarketCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    
    cell.model = self.mainArray[indexPath.row];
    
    return cell;
}

@end
